package com.zjhcsoft.auth.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dc.eai.data.*;
import com.dcfs.esb.utils.TLSimRepTools;
import com.zjhcsoft.auth.common.enums.ApiCode;
import com.zjhcsoft.auth.common.enums.PasswordType;
import com.zjhcsoft.auth.common.vo.Result;
import com.zjhcsoft.auth.entity.Corporation;
import com.zjhcsoft.auth.entity.Password;
import com.zjhcsoft.auth.entity.User;
import com.zjhcsoft.auth.entity.UserDevice;
import com.zjhcsoft.auth.entity.web.*;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * @author wzya
 * @date 2021/03/18
 */
public class ResultUtil {

    public static Object xmlToApiRequest(CompositeData requestCd){
        //CompositeData requestCd = TLSimRepTools.xmlToCD(requestXml.getBytes(StandardCharsets.UTF_8), "utf-8");
        CompositeData appHead = requestCd.getStruct("APP_HEAD");
        CompositeData sysHead = requestCd.getStruct("SYS_HEAD");
        CompositeData data = requestCd.getStruct("BODY");


        String apiCode = sysHead.getField("SERVICE_CODE").strValue();
        String serviceCode = sysHead.getField("SERVICE_SCENE").strValue();;
        //注册
        if(ApiCode.REGISTER.getCode().equals(apiCode+serviceCode)){
            RegisterRequest request = new RegisterRequest();
            /*头信息*/
            request.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            request.setGlobalId((String) getField(data,"GLOBAL_ID"));
            request.setGlobalType((String)getField(data,"GLOBAL_TYPE"));
            request.setClientName((String)getField(data,"CLIENT_NAME"));
            request.setGender((String)getField(data,"GENDER"));
            request.setMobile((String)getField(data,"MOBILE"));
            request.setPassword((String)getField(data,"PASSWORD"));
            request.setClientNo((String)getField(data,"CLIENT_NO"));
            request.setSmsVrfcCd((String)getField(data,"SMS_VRFC_CD"));
            request.setNickName((String)getField(data,"ALIAS"));
            request.setSeId((String)getField(data,"SE_ID"));
            Array acctArray = data.getArray("USER_LOGIN_INFO_ARRAY");
            List<RegisterAcct> acctList = new ArrayList<>();
            for (int i = 0; i < acctArray.size(); i++)
            {
                CompositeData acctData = acctArray.getStruct(i);
                RegisterAcct acct = new RegisterAcct();
                acct.setAcctNo((String)getField(acctData,"LOGIN_NO"));
                acct.setAcctType((String)getField(acctData,"DATA_TP"));
                acctList.add(acct);
            }
            request.setRegisterAcctArray(acctList);

            Array channelArray = data.getArray("CHANNEL_INFO_ARRAY");
            List<RegisterChannel> channels = new ArrayList<>();
            for (int i = 0; i < channelArray.size(); i++)
            {
                CompositeData channelData = channelArray.getStruct(i);
                RegisterChannel channel = new RegisterChannel();
                channel.setChannelCode((String)getField(channelData,"CHANNEL_CODE"));
                channel.setChannelName((String)getField(channelData,"CHANNEL_NAME"));
                channels.add(channel);
            }
            request.setChannelArray(channels);
            return request;
        }
        //静态密码登录
        if(ApiCode.STATIC_LOGIN.getCode().equals(apiCode+serviceCode)){
            RegisterRequest request = new RegisterRequest();
            /*头信息*/
            LoginRequest loginRequest = new LoginRequest();
            loginRequest.setUserCredential((String) getField(data,"LOGIN_NO"));
            loginRequest.setPassword((String) getField(data,"PASSWORD"));
            loginRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            loginRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            return loginRequest;
        }
        //会话保持
        if(ApiCode.LOGIN_KEEP.getCode().equals(apiCode+serviceCode) || ApiCode.EXIT.getCode().equals(apiCode+serviceCode)){
            String token = (String) getField(data,"OTP_CODE");
            return token;
        }
        //静态密码登录
        if(ApiCode.PASSWORD_POLICY_CHECK.getCode().equals(apiCode+serviceCode)){
            /*头信息*/
            PasswordPolicyRequest passwordPolicyRequest = new PasswordPolicyRequest();
            passwordPolicyRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            passwordPolicyRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            passwordPolicyRequest.setPassword((String) getField(data,"PASSWORD"));
            return passwordPolicyRequest;
        }
        //密码校验方式查询
        if(ApiCode.QUERY_CHECK_TYPES.getCode().equals(apiCode+serviceCode)){
            QueryCheckTypesRequest queryCheckTypesRequest = new QueryCheckTypesRequest();
            queryCheckTypesRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            queryCheckTypesRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            queryCheckTypesRequest.setUserCredential((String) getField(data,"LOGIN_NO"));
            return queryCheckTypesRequest;
        }
        //开启关闭密码校验方式
        if(ApiCode.UPDATE_CHECK_TYPES.getCode().equals(apiCode+serviceCode)){
            UpdateCheckTypeRequest updateCheckTypeRequest = new UpdateCheckTypeRequest();
            updateCheckTypeRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            updateCheckTypeRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            updateCheckTypeRequest.setUserCredential((String) getField(data,"LOGIN_NO"));
            updateCheckTypeRequest.setOperatorType((String) getField(data,"OPERATION_TYPE"));
            updateCheckTypeRequest.setPassword((String) getField(data,"PASSWORD"));
            updateCheckTypeRequest.setCheckType((String) getField(data,"CHCK_TP"));
            return updateCheckTypeRequest;
        }
        //用户查询
        if(ApiCode.USET_INFO.getCode().equals(apiCode+serviceCode)){
            QueryUserInfoRequest queryUserInfoRequest = new QueryUserInfoRequest();
            queryUserInfoRequest.setUserCredential((String) getField(data,"LOGIN_NO"));
            queryUserInfoRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            queryUserInfoRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            return queryUserInfoRequest;
        }
        //多法法人查询
        if(ApiCode.QUERY_CORPORATION.getCode().equals(apiCode+serviceCode)){
            QueryCorporationRequest queryCorporationRequest = new QueryCorporationRequest();
            queryCorporationRequest.setUserCredential((String) getField(data,"LOGIN_NO"));
            queryCorporationRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            queryCorporationRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            return queryCorporationRequest;
        }
        //设备查询
        if(ApiCode.DEVICE.getCode().equals(apiCode+serviceCode)){
            QueryDeviceRequest queryDeviceRequest = new QueryDeviceRequest();
            queryDeviceRequest.setUserCredential((String) getField(data,"LOGIN_NO"));
            queryDeviceRequest.setChannelCode((String) getField(sysHead,"ORG_SYS_ID"));
            queryDeviceRequest.setCorporationCode((String) getField(sysHead,"CORP_CODE"));
            return queryDeviceRequest;
        }
        return null;
    }

    public static String responseToXml(Result result){
        String xml = "";
        if("register".equals(result.getType())){
            CompositeData resCd = new CompositeData();
            JSONObject data = (JSONObject)result.getData();
            String userId = data.getString("userId");
            Field fd = new Field(new FieldAttr(FieldType.FIELD_STRING,11,0));
            fd.setValue(userId);
            resCd.addField("BODY",fd);
            xml = String.valueOf(TLSimRepTools.CDtoXml(resCd,"utf-8"));
        }
        return  xml;
    }




    private static Object getField( CompositeData data ,String fieldName){
        try {
            return data.getField(fieldName).getValue();
        }catch (Exception e){
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            //通过绝对路径获取文件
            String s1 = MyUtils.readFile(new File("C:\\Users\\wzya\\Desktop\\request.xml"));
            // System.out.println(JSON.toJSONString(xmlToApiRequest(s1)));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Result result = Result.ok(RandomUtils.randomStr(16));
        System.out.println(responseToXml(result));
    }



    public static String getBodyForAuth (List<String> errList, CompositeData sysData ,CompositeData appDate,Result result) {
        CompositeData respCD = getRespCD(errList, sysData, appDate, null, result);
        String resultMsg = TLSimRepTools.parseCD(respCD);
        return resultMsg;
    }

    public static CompositeData getRespCD (List<String> errList, CompositeData sysData ,CompositeData appData, String rspCode, Result result) {
        CompositeData respCD = new CompositeData();
        //SYS_HEAD
        CompositeData syshead = new CompositeData();
        respCD.addStruct("SYS_HEAD", syshead);
        //服务码
        addField(syshead,"SERVICE_CODE","string",11,(String) sysData.getField("SERVICE_CODE").getValue());
        //服务场景
        addField(syshead,"SERVICE_SCENE","string",2,(String) sysData.getField("SERVICE_SCENE").getValue());
        //交易流水号
        addField(syshead,"CONSUMER_SEQ_NO","string",52,(String) sysData.getField("CONSUMER_SEQ_NO").getValue());
        //交易日期
        addField(syshead,"TRAN_DATE","string",8,dateToString(new Date(),"YYYYMMdd"));
        //交易时间
        addField(syshead,"TRAN_TIMESTAMP","string",6,dateToString(new Date(),"HHmmss"));
        //请求系统编号
        addField(syshead,"CONSUMER_ID","string",6,(String) sysData.getField("CONSUMER_ID").getValue());
        //响应系统编号
        addField(syshead,"PROVIDER_ID","string",6,(String) sysData.getField("PROVIDER_ID").getValue());
        //APP_HEAD
        CompositeData apphead = new CompositeData();
        respCD.addStruct("APP_HEAD", apphead);
        //业务流水号
        addField(apphead,"BUSS_SEQ_NO","string",52,(String) appData.getField("BUSS_SEQ_NO").getValue());
        //服务处理返回流水号
        addField(apphead,"SERV_SEQ_NO","string",52,(String) appData.getField("BUSS_SEQ_NO").getValue());
        //BODY
        CompositeData body = new CompositeData();
        respCD.addStruct("BODY", body);

        if("0".equals(String.valueOf(result.getCode()))){
            if(ApiCode.REGISTER.getName().equals(result.getType())){
                JSONObject data = (JSONObject)result.getData();
                String userId = data.getString("userId");
                addField(body,"USER_NO","string",32,userId);
            }
            if(ApiCode.STATIC_LOGIN.getName().equals(result.getType())){
                LoginResponse data = (LoginResponse)result.getData();
                addField(body,"DESCRIPTION","string",512,data.getDescription());
                addField(body,"ACRDTN_TCKT","string",128,data.getAcrdtnTckt());
                addField(body,"ACRDTN_MAP","string",32,data.getAcrdtnMap());
                addField(body,"ACRDTN_LVL","string",32,data.getAcrdtnLvl());
                addField(body,"OTP_MSG","string",32,data.getOtpMsg());
                addField(body,"ACCT_STATUS","string",32,data.getClientStatus());
                addField(body,"CONTINUOUS_ERROR_TIMES","string",32,data.getContinuousErrorTimes());
                addField(body,"TODAY_ERROR_TIMES","string",32,data.getTodayErrorTimes());
                addField(body,"CLIENT_NO","string",32,data.getClientNo());
                addField(body,"BIND_FLAG","string",32,data.getIsBind());
                addField(body,"BND_MBL","string",32,data.getClientNo());
                addField(body,"REAL_NM_ACRDTN_FLG","string",32,data.getAcrdtnLvl());
                addField(body,"OPEN_FLAG","string",32,data.getClientNo());
            }
            if(ApiCode.QUERY_CHECK_TYPES.getName().equals(result.getType())){
                Array acrtdnInfoArray = new Array();//ACRDTN_INFO_ARRAY
                if(result.getData() != null){
                    for(Password pwd : (List<Password>)result.getData()){
                        CompositeData r =  new CompositeData();
                        //CHCK_TP
                        addField(r,"CHCK_TP","string",10,pwd.getCheckType());
                        //OPEN_CLOSE
                        addField(r,"OPEN_CLOSE","string",10,pwd.getPasswordStatus());
                        acrtdnInfoArray.addStruct(r);
                    }
                }
                body.addArray("ACRDTN_INFO_ARRAY", acrtdnInfoArray);
            }
            if(ApiCode.UPDATE_CHECK_TYPES.getName().equals(result.getType())){
                String pwsd = (String)result.getData();
                addField(body,"PSWD_CPHRTXT","string",255,pwsd);
            }
            if(ApiCode.QUERY_CORPORATION.getName().equals(result.getType())){
                Array array = new Array();//CO_LEGEL_RPRSN_INFO_ARRAY
                if(result.getData() != null){
                    for(Corporation corporation : (List<Corporation>)result.getData()){
                        CompositeData r =  new CompositeData();
                        //法人代码
                        addField(r,"LEGAL_CD","string",10,corporation.getCorporationCode());
                        //法人姓名
                        addField(r,"LGL_PRSN_NM","string",10,corporation.getCorporationName());
                        array.addStruct(r);
                    }
                }
                body.addArray("CO_LEGEL_RPRSN_INFO_ARRAY", array);
            }
            //用户详情查询
            if(ApiCode.USET_INFO.getName().equals(result.getType())){
                User data = (User)result.getData();
                addField(body,"GLOBAL_ID","string",60,data.getGlobalId());
                addField(body,"GLOBAL_TYPE","string",5,data.getGlobalType());
                addField(body,"CLIENT_NAME","string",200,data.getClientName());
                addField(body,"GENDER","string",1,data.getGender());
                addField(body,"MOBILE","string",16,data.getMobile());
                addField(body,"CLIENT_NO","string",20,data.getClientNo());
                addField(body,"RGST_RGST_DT","string",8,dateToString(data.getRegisterTime(),"yyyyddmm"));
            }
            //用户详情查询
            if(ApiCode.DEVICE.getName().equals(result.getType())){
                Array array = new Array();//MCHN_EQMT_INFO_ARRAY
                if(result.getData() != null){
                    for(UserDevice userDevice : (List<UserDevice>)result.getData()){
                        CompositeData r =  new CompositeData();
                        addField(r,"SE_ID","string",60,userDevice.getSeId());
                        addField(r,"LOGIN_NO","string",5,userDevice.getLoginNo());
                        addField(r,"BND_TMSTMP","string",8,dateToString(userDevice.getBindingTime(),"yyyyddmm"));
                        array.addStruct(r);
                    }
                }
                body.addArray("MCHN_EQMT_INFO_ARRAY", array);
            }

            addField(body,"DESCRIPTION","string",512,"处理成功");
            addField(syshead,"RET_STATUS","string",1,"S");
            Array ret = new Array();
            CompositeData r =  new CompositeData();
            //RET_CODE
            addField(r,"RET_CODE","string",6,String.valueOf("000000"));
            //RET_MSG
            addField(r,"RET_MSG","string",6,"处理成功");
            ret.addStruct(r);
            syshead.addArray("RET", ret);
        }else{
            addField(syshead,"RET_STATUS","string",1,"F");
            Array ret = new Array();
            CompositeData r =  new CompositeData();
            //RET_CODE
            addField(r,"RET_CODE","string",6,String.valueOf("999999"));
            //RET_MSG
            addField(r,"RET_MSG","string",6,result.getMsg());
            ret.addStruct(r);
            syshead.addArray("RET", ret);
        }
        return respCD;
    }

    /**
     * 添加Filed到CD
     * @param cd     添加目标CD对象
     * @param name   添加字段名称
     * @param type   添加字段类型
     * @param length 添加字段长度
     * @param value  添加字段值
     */
    private static void addField(CompositeData cd,String name,String type,int length,String value){
        Field field= new Field(new FieldAttr(getType(type), length));
        field.setValue(value);
        cd.addField(name, field);
    }

    /**
     * 获取数据类型
     */
    private static FieldType getType(String type){
        if("int".equalsIgnoreCase(type)) {
            return FieldType.FIELD_INT;
        }
        else if("image".equalsIgnoreCase(type)){
            return FieldType.FIELD_IMAGE;
        }
        else {
            return FieldType.FIELD_STRING;
        }
    }

    private static String dateToString(Date date, String pattern){
        if(date == null){
            return "";
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(date);
        }
    }
}
